package com.utilviet.baovn;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.utilviet.baovn.objects.DataBase;

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * Created by leanhtai on 6/21/15.
 */
public class MenuFragment extends Fragment {
    private ExpandableListView mListView = null;
    private ListViewAdapter mListViewAdapter = new ListViewAdapter();
    private static final int FAVORITE_GROUP_INDEX = 0;

    private EditText mSearchEditText = null;
    private Button mSearchClearButton = null;

    private LayoutInflater mInflater = null;

    public IMenuFragment mIMenuFragment = null;

    private ArrayList<HashMap<String, String>> mOriginalFavoriteWebs = null;
    private ArrayList<HashMap<String, String>> mOriginalOtherWebs = null;
    private ArrayList<HashMap<String, String>> mFavoriteWebs = null;
    private ArrayList<HashMap<String, String>> mOtherWebs = null;

    private boolean mEditing = false;
    private int mCountPromoteWebs = 0;
    private int mCountDemoteWebs = 0;
    private Button mEditButton = null;
    private Button mCancelButton = null;

    private int prevSearchTextLen = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;

        View view = inflater.inflate(R.layout.menu_fragment, container, false);

        mCancelButton = (Button) view.findViewById(R.id.cancelButton);
        mCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.post(new Runnable() {
                    @Override
                    public void run() {
                        mEditing = false;
                        changedEditMode(false);
                    }
                });
            }
        });

        //
        mEditButton = (Button) view.findViewById(R.id.editButton);
        mEditButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                v.post(new Runnable() {
                    @Override
                    public void run() {
                        boolean edit = !mEditing;

                        // Start edit
                        if (edit) {
                            mEditing = true;
                            changedEditMode(edit);
                        }
                        // Save edit
                        else {
                            changedEditMode(edit);
                            mEditing = false;
                        }
                    }
                });
            }
        });

        mSearchClearButton = (Button)view.findViewById(R.id.searchClearButton);
        mSearchClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchEditText.setText("");

                resetSearch();
            }
        });

        mSearchEditText = (EditText)view.findViewById(R.id.searchEditText);
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                String searchText = s.toString();

                int searchLen = 0;

                if (searchText != null) {
                    searchLen = searchText.length();
                }

                if (searchLen > 0) {
                    showClearSearchButton(View.VISIBLE);

                    if (searchLen > 1) {
                        // favorite webs
                        ArrayList array = mFavoriteWebs;
                        if (searchLen < prevSearchTextLen) {
                            array = mOriginalFavoriteWebs;
                        }

                        ArrayList webs = searchFavoriteWebs(searchText, array);
                        mFavoriteWebs = webs;

                        // other webs
                        array = mOtherWebs;
                        if (searchLen < prevSearchTextLen) {
                            array = mOriginalOtherWebs;
                        }

                        webs = searchOtherWebs(searchText, array);
                        mOtherWebs = webs;

                        prevSearchTextLen = searchLen;
                    }
                    else {
                        ArrayList webs = searchFavoriteWebs(searchText, mOriginalFavoriteWebs);
                        mFavoriteWebs = webs;

                        webs = searchOtherWebs(searchText, mOriginalOtherWebs);
                        mOtherWebs = webs;

                        prevSearchTextLen = 0;
                    }

                    System.gc();
                    mListViewAdapter.notifyDataSetChanged();
                }
                else {
                    resetSearch();
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });

        mListView = (ExpandableListView) view.findViewById(R.id.listView);
        mListView.setGroupIndicator(null);
        mListView.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
        mListView.setAdapter(mListViewAdapter);

        mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                // Remove highlight on childView
                mListView.setItemChecked(-1, true);

                return true;
            }
        });

        mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @SuppressWarnings("unchecked")
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                // Checked
                int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
                parent.setItemChecked(index, true);

                //
                selectItemAt(groupPosition, childPosition);

                return true;
            }
        });

        new LoadDataBaseTask().execute();

        return view;
    }

    private ArrayList<HashMap<String, String>> searchFavoriteWebs(String searchText, ArrayList<HashMap<String, String>> array) {
        ArrayList<HashMap<String, String>> webs = new ArrayList<>();

        for (HashMap<String, String> hashMap : array) {
            String iconName = hashMap.get("icon");

            if (iconName.contains(searchText)) {
                webs.add(hashMap);
            }
        }

        return webs;
    }

    private ArrayList<HashMap<String, String>> searchOtherWebs(String searchText, ArrayList<HashMap<String, String>> array) {
        ArrayList<HashMap<String, String>> webs = new ArrayList<>();

        for (HashMap<String, String> hashMap : array) {
            String iconName = hashMap.get("icon");

            if (iconName.contains(searchText)) {
                webs.add(hashMap);
            }
        }

        return webs;
    }

    private void showClearSearchButton(int viewMode) {
        if (mSearchClearButton != null) {
            mSearchClearButton.setVisibility(viewMode);
        }
    }

    private void resetSearch() {
        showClearSearchButton(View.INVISIBLE);

        mFavoriteWebs.clear();
        mFavoriteWebs.addAll(mOriginalFavoriteWebs);

        mOtherWebs.clear();
        mOtherWebs.addAll(mOriginalOtherWebs);

        mListViewAdapter.notifyDataSetChanged();
    }

    private void changedEditMode(boolean edit) {
        // Start edit
        if (edit == true) {
            mEditButton.setText(R.string.save_lable);
        }
        // Save edit
        else {
            if (mCountDemoteWebs > 0 || mCountPromoteWebs > 0) {
                int countDemoteWebsTmp = mCountDemoteWebs;
                int countPromoteWebsTmp = mCountPromoteWebs;

                //
                int nOldFavWebsSize = mFavoriteWebs.size();

                // Promote web to favorite
                int i = 0;
                while (countPromoteWebsTmp > 0 && i < mOtherWebs.size()) {
                    HashMap<String, String> webInfo = mOtherWebs.get(i);
                    String marked = webInfo.get(DataBase.KEY_MARKED);

                    if (marked != null && marked.equals(DataBase.MARKED_VALUE)) {
                        if (mEditing) {
                            mFavoriteWebs.add(webInfo);
                            mOtherWebs.remove(i);

                            mOriginalFavoriteWebs.add(webInfo);
                            mOriginalOtherWebs.remove(webInfo);
                        }
                        // cancel edit
                        else {
                            webInfo.put(DataBase.KEY_MARKED, DataBase.UNMARKED_VALUE);
                        }

                        countPromoteWebsTmp --;
                    }
                    else {
                        i ++;
                    }
                }

                // Demote favorite to other web
                i = nOldFavWebsSize-1;
                while (countDemoteWebsTmp > 0 && i >= 0) {
                    HashMap<String, String> webInfo = mFavoriteWebs.get(i);
                    String marked = webInfo.get(DataBase.KEY_MARKED);

                    if (marked != null && marked.equals(DataBase.UNMARKED_VALUE)) {
                        if (mEditing) {
                            mOtherWebs.add(webInfo);
                            mFavoriteWebs.remove(i);

                            mOriginalOtherWebs.add(webInfo);
                            mOriginalFavoriteWebs.remove(webInfo);
                        }
                        // cancel edit
                        else {
                            webInfo.put(DataBase.KEY_MARKED, DataBase.MARKED_VALUE);
                        }

                        countDemoteWebsTmp --;
                    }

                    i --;
                }
            }

            DataBase.sortByKey(mOtherWebs, DataBase.KEY_ICON);

            mEditButton.setText(R.string.edit_lable);
        }

        mListViewAdapter.notifyDataSetChanged();
        mCancelButton.setVisibility(edit ? View.VISIBLE : View.INVISIBLE);

        if (mCountDemoteWebs > 0 || mCountPromoteWebs > 0) {
            saveDataBaseTask();
        }

        mCountDemoteWebs = 0;
        mCountPromoteWebs = 0;
    }

    private void selectItemAt(int group, int row) {
        HashMap<String, String> website = (HashMap<String, String>) mListViewAdapter.getChild(group, row);
        if (website != null) {
            Log.d("Menu", "Tap on item" + website);
            if (mIMenuFragment != null) {
                mIMenuFragment.menuDidPressedWebSite(MenuFragment.this,website);
            }
        }
    }

    private class ListViewAdapter extends BaseExpandableListAdapter {
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            if (groupPosition == FAVORITE_GROUP_INDEX) {
                if (mFavoriteWebs == null) {
                    return null;
                }

                return mFavoriteWebs.get(childPosition);
            }

            if (mOtherWebs == null) {
                return null;
            }

            return mOtherWebs.get(childPosition);
        }

        @Override
        public long getChildId(int arg0, int arg1) {
            return 0;
        }

        @Override
        public View getChildView(final int groupPosition, int childPosition, boolean arg2, View convertView, ViewGroup parent) {
            //
            convertView = mInflater.inflate(R.layout.menu_listview_child_view, null);

            if (convertView == null) {
                return null;
            }

            //
            HashMap<String, String> webSiteInfo = (HashMap<String, String>)getChild(groupPosition, childPosition);

            ImageView logoImageView = (ImageView) convertView.findViewById(R.id.logoImageView);
            if (logoImageView != null && webSiteInfo != null) {
                logoImageView.setImageResource( getActivity().getResources().getIdentifier(webSiteInfo.get("icon"), "drawable", getActivity().getPackageName()) );
            }

            //
            ImageView favImageView = (ImageView) convertView.findViewById(R.id.favImageView);
            favImageView.setTag(new WeakReference<HashMap<String, String>>(webSiteInfo));

            favImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mEditing == true) {
                        HashMap<String, String> web = null;

                        WeakReference webRef = (WeakReference)v.getTag();
                        if (webRef != null) {
                            web = (HashMap<String, String>)webRef.get();
                        }

                        String markedValue = null;
                        if (web != null) {
                            markedValue = web.get(DataBase.KEY_MARKED);
                        }

                        if (markedValue != null && markedValue.equals(DataBase.MARKED_VALUE)) {
                            updateIconFav((ImageView) v, false);

                            web.put(DataBase.KEY_MARKED, DataBase.UNMARKED_VALUE);

                            if (groupPosition == FAVORITE_GROUP_INDEX) {
                                mCountDemoteWebs ++;
                            }
                            else {
                                mCountPromoteWebs--;
                            }
                        }
                        else {
                            updateIconFav((ImageView) v, true);
                            web.put(DataBase.KEY_MARKED, DataBase.MARKED_VALUE);

                            if (groupPosition == FAVORITE_GROUP_INDEX) {
                                mCountDemoteWebs --;
                            }
                            else {
                                mCountPromoteWebs++;
                            }
                        }
                    }
                }
            });

            if (mEditing == true) {
                favImageView.setVisibility(View.VISIBLE);

                String marked = webSiteInfo.get(DataBase.KEY_MARKED);

                if (marked != null && marked.equals(DataBase.MARKED_VALUE)) {
                    updateIconFav(favImageView, true);
                }
                else {
                    updateIconFav(favImageView, false);
                }
            }
            else {
                favImageView.setVisibility(View.INVISIBLE);
            }

            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            if (groupPosition == FAVORITE_GROUP_INDEX) {
                if (mFavoriteWebs != null) {
                    return mFavoriteWebs.size();
                }

                return 0;
            }

            if (mOtherWebs != null) {
                return mOtherWebs.size();
            }

            return 0;
        }

        @Override
        public Object getGroup(int groupPosition) {
            if (groupPosition == FAVORITE_GROUP_INDEX) {
                return "Trang yêu thích";
            }

            return "Trang khác";
        }

        @Override
        public int getGroupCount() {
            return 2;
        }

        @Override
        public long getGroupId(int arg0) {
            return 0;
        }

        @Override
        @SuppressLint("InflateParams")
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.menu_listview_group_view, null);

            if (convertView == null) {
                return null;
            }

            TextView title = (TextView) convertView.findViewById(R.id.groupTitleTextView);
            if (title != null) {
                title.setText((String) getGroup(groupPosition));
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int arg0, int arg1) {
            return true;
        }
    }

    private void updateIconFav(ImageView favImageView, boolean favOn) {
        if (favOn) {
            favImageView.setImageResource(R.drawable.icon_favorite);
            favImageView.clearColorFilter();
        }
        else {
            favImageView.setImageResource(R.drawable.icon_favorite_dis);
            favImageView.setColorFilter(R.color.light_grey_color);
        }
    }

    private class LoadDataBaseTask extends AsyncTask<String, Void, Boolean> {
        ArrayList<HashMap<String, String>> favoriteWebsites = new ArrayList<HashMap<String, String>>();
        ArrayList<HashMap<String, String>> otherWebsites = new ArrayList<HashMap<String, String>>();

        protected Boolean doInBackground(String... parameters) {
            try {
                // Load favorite website
                ArrayList<String> favoriteWebIds = DataBase.loadRef(getActivity());

                // Load json data
                return DataBase.loadDefault(getActivity(), favoriteWebIds, favoriteWebsites, otherWebsites);
            }
            catch (Exception e) {
                e.printStackTrace();
            }

            return false;
        }

        protected void onPostExecute(Boolean ret) {
            try {
                // backup data
                mOriginalFavoriteWebs = favoriteWebsites;
                mOriginalOtherWebs = otherWebsites;

                if (mFavoriteWebs != null) {
                    mFavoriteWebs.clear();
                }
                else {
                    mFavoriteWebs = new ArrayList<>();
                }

                mFavoriteWebs.addAll(favoriteWebsites);

                if (mOtherWebs != null) {
                    mOtherWebs.clear();
                }
                else {
                    mOtherWebs = new ArrayList<>();
                }
                mOtherWebs.addAll(otherWebsites);

                mListViewAdapter.notifyDataSetChanged();

                mListView.expandGroup(0);
                mListView.expandGroup(1);

                if (mListView.getCheckedItemPosition() < 0) {
                    // Find default item
                    int childPos = 0;
                    int groupPos = 0;
                    int checkedPos = 1;

                    if (mOriginalFavoriteWebs == null || mOriginalFavoriteWebs.size() == 0) {
                        groupPos = 1;
                        checkedPos = 2;
                    }

                    mListView.setItemChecked(checkedPos, true);
                    selectItemAt(groupPos, childPos);
                }
            }
            finally {
                System.gc();
            }
        }
    }

    @Override
    public void onDestroyView() {
        saveDataBaseTask();

        super.onDestroyView();
    }

    private void saveDataBaseTask() {
        if (mOriginalFavoriteWebs == null) {
            return;
        }

        ArrayList<String> favoriteWebIds = new ArrayList<String>();

        for (int i = 0; i < mOriginalFavoriteWebs.size(); i ++) {
            HashMap<String, String> website = mOriginalFavoriteWebs.get(i);

            String id = website.get("id");

            if (id != null) {
                favoriteWebIds.add(id);
            }
        }

        DataBase.saveRef( getActivity(), favoriteWebIds );
    }
}
